//
// Created by afly on 20-12-23.
// Private Mail: a_fly0505@163.com
// QQ: 785230837 WX: afly003
// Company: juefx 
// Copyright (c) 2020 juefx all rigths reserved
//

#include "common/common.h"
#include "events_wait.hpp"

namespace jfx {

    int EventsWait::Wait(const int time_out_ms) {
        if(m_signals.load() <= 0){
            return EVENTS_FAIL;
        }

        std::unique_lock<std::mutex> ul(m_mtx);
        if (time_out_ms >= 0) {
            std::chrono::milliseconds wait_time_ms(time_out_ms);
            auto result = m_cv.wait_for(ul, wait_time_ms, [&]{ return m_signals.load() <= 0; });
            if (result) {
                return EVENTS_SUCCESS;
            }
            return EVENTS_TIME_OUT;
        }
        m_cv.wait(ul, [&]{ return m_signals.load() <= 0; });
        LOG(INFO) << "events awake";
        return EVENTS_SUCCESS;
    }

    void EventsWait::Signal(const int count) {
        if(m_signals > 0){
//            std::unique_lock<std::mutex> ul(m_mtx);
            m_signals.fetch_sub(count);
            m_cv.notify_one();
            LOG(INFO) << "events signal=" << m_signals.load();
        }
    }
    void EventsWait::Add(const int count) {
        m_signals.fetch_add(count);
    }
}
